<?php

namespace App\Http\Middleware;

use App\Validators\Gateway\RechargeGatewayValidator;
use Closure;
use Prettus\Validator\Exceptions\ValidatorException;

class CheckoutPay
{
    protected $gatewayValidator;

    public function __construct(RechargeGatewayValidator $gatewayValidator)
    {
        $this->gatewayValidator = $gatewayValidator;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        try {
            $data = $request->all(array_keys($this->gatewayValidator->getRules('checkout')));
            $this->gatewayValidator->with($data)->passesOrFail('checkout');
            $token = $request->input('postToken');

            $session = $request->session()->get('post_token');
            if ($session == null || $token != $session) {
                return redirect()->route('gateway.recharge.error');
            }
        } catch (ValidatorException $exception) {
            return redirect()->route('gateway.recharge.error');
        } catch (\Exception $exception) {
            dd($exception);
        }
        return $next($request);
    }
}
